#pragma once
#include"DataManger.hpp"
#include"httplib.h"
namespace shw
{
#define TIME_GAP 3
#define SERVER_IP "101.42.165.160"
#define SERVER_PORT 8080
#define BACK_DIR "./backdir"
	class BackUp
	{
	private:
		std::string _back_dir;
		Datamanger* _data;
	public:
		BackUp(const std::string& back_dir= BACK_DIR) :_back_dir(back_dir)
		{
			_data = new Datamanger;
			icloud::FileUtil fut(_back_dir);
			fut.CreDir();
		}
		~BackUp() { delete _data; }
		std::string GetId(const std::string filename)
		{
			std::stringstream ss;
			icloud::FileUtil fut(filename);
			ss << fut.GetFileName() << "-" << fut.GetFileSize() << "-" << fut.LastMTime();
			std::string res = ss.str();
			return res;
		}
		bool IsNeedLoad(const std::string& filename)
		{
			std::string id;
			if (_data->GetByKey(filename, id))
			{
				std::string new_id = GetId(filename);
				if(id==new_id)
				{
					return false;
				}
			}
			icloud::FileUtil fut(filename);
			if (time(NULL) - fut.LastMTime() > TIME_GAP)
			{
				return true;
			}
			return false;
		}
		bool UpLoad(const std::string& filename)
		{
			icloud::FileUtil fut(filename);
			httplib::Client cilent(SERVER_IP, SERVER_PORT);
			httplib::MultipartFormData item;
			std::string body; 
			fut.GetContent(body);
			item.content = body;
			item.filename = fut.GetFileName();
			item.name = "file";
			item.content_type = "application / octet - stream";
			httplib::MultipartFormDataItems items;
			items.push_back(item);
			auto res = cilent.Post("/upload", items);
			if (!res || res->status != 200)
			{
				return false;
			}
			return true;
		}
		
		void Module()
		{
			while (1)
			{
				std::vector<std::string> arr;
				icloud::FileUtil fut(_back_dir);
				fut.ScanDir(arr);
				for (auto& it : arr)
				{
					if (!IsNeedLoad(it)) { continue; }
					if (UpLoad(it))
					{
						std::string id = GetId(it);
						_data->Insert(it, id);
					}
				}
				usleep(1000);
			}
		}
	};
}